package util

import (
	"bytes"
	"encoding/json"
	"errors"
	"io/ioutil"
	"log"
	"net/http"
)

const BaseUrl = "https://core.ztn-tech.com/"
var Token string

type BaseRes struct {
	Data interface{} `json:"data"`
	Code string      `json:"code"`
	msg  string      `json:"msg"`
}

func PostJson(path string, param interface{}) ([]byte, error) {
	var url = BaseUrl + path
	jsonBytes, err := json.Marshal(param)
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonBytes))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("access-token", Token)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Printf("%s is err", url)
		return nil, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != 200 {
		log.Printf("%s is err", url)
		return nil, err
	}
	var body, _ = ioutil.ReadAll(resp.Body)
	var baseRes BaseRes
	err = json.Unmarshal(body, &baseRes)
	if err != nil {
		log.Println(err)
		return nil, err
	}
	if baseRes.Data != nil {
		bytes, err := json.Marshal(baseRes.Data)
		if err != nil {
			log.Println(err)
			return bytes, err
		}
		if err != nil {
			log.Println(err)
			return bytes, err
		}
		return bytes, err
	}
	return nil, errors.New("data == null")

}
